using System;
using System.Xml;
using System.Diagnostics;
using CKS.EBE.API;
using Microsoft.SharePoint;

namespace CKS.EBE.WebControls
{
	public class Post : XmlBasedControl
	{
		public string IncludeLists { get; set; }

		protected override XmlDocument BuildDocument()
		{
			try
			{
				SPList oList = Helper.GetListByFolderName(Web, Localization.GetListName(Localization.BlogList.Posts, Web.Language));
				SPListItem oPost;
				if (Page.Request["ID"] == null)
				{
					oPost = Helper.GetPostFromUrl(Page.Request.Url.AbsoluteUri, Web);
					if (oPost == null) throw new ArgumentException("The post ID is null");
				}
				else
				{
					try
					{
						oPost = oList.GetItemById(int.Parse(Page.Request["id"]));
					}
					catch (ArgumentException ex)
					{
						Trace.WriteLine(ex);
						throw new ArgumentException("The post ID is invalid", ex);
					}
				}

				if ((DateTime)oPost["PublishedDate"] > DateTime.Now)
				{
					// only show posts which are published if we are not a contributor or owner
					if (BlogContext.Current.IsBlogContributor == false || BlogContext.Current.IsBlogOwner == false)
						throw new InvalidOperationException("The post ID is invalid");
				}

				string sListsXml = "";

				if (!string.IsNullOrEmpty(IncludeLists))
					sListsXml = AddIncludedLists(sListsXml);

				XmlDocument oDoc = new XmlDocument();
				oDoc.LoadXml("<Post>" + oPost.Xml + "</Post>");
				CleanXml(oDoc);

				if (!string.IsNullOrEmpty(sListsXml))
				{
					XmlDocument oLists = new XmlDocument();
					oLists.LoadXml(sListsXml);
					oDoc.DocumentElement.AppendChild(oDoc.ImportNode(oLists.DocumentElement, true));
				}

				return oDoc;
			}
			catch (Exception ex)
			{
				Trace.WriteLine(ex);

				XmlDocument oError = new XmlDocument();
				oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
				return oError;
			}
		}

		private string AddIncludedLists(string sListsXml)
		{
			try
			{
				string[] arLists = IncludeLists.Split(',');
				foreach (string sList in arLists)
				{
					XmlDocument oCleanedXml = CleanXml(Web.Lists[sList].Items.Xml);
					oCleanedXml.DocumentElement.SetAttribute("ListName", sList);
					sListsXml += oCleanedXml.OuterXml;
				}
			}
			catch { }
			return sListsXml;
		}
	}
}